package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ev.framework.utils.*;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3PPBomSynService;
import com.ev.k3cloudBusiness.vo.PPBomEntryVO;
import com.ev.k3cloudBusiness.vo.PPBomVO;
import com.ev.mes.domain.ProductionFeedingDO;
import com.ev.mes.domain.ProductionFeedingDetailDO;
import com.ev.mes.service.ProductionFeedingDetailService;
import com.ev.mes.service.ProductionFeedingService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 姚家乐
 * @since 2021/5/31 9:50
 */
@Service
@Slf4j
public class K3PPBomSynServiceImpl implements K3PPBomSynService {

    @Autowired
    ProductionFeedingService       productionFeedingService;

    @Autowired
    ProductionFeedingDetailService productionFeedingDetailService;
    @Autowired
    kingdeeMiddlewareService       kingdeeMiddlewareService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R PPBomSyn() {
        String materialResult = kingdeeMiddlewareService.PPBomAll();
        List<ProductionFeedingDO> productionFeedingDOList = productionFeedingService.listAll();

        JSONObject resultObj = JSON.parseObject(materialResult);
        if (!resultObj.getString("code").equals("0")) {
            log.info(resultObj.getString("msg"));
            return R.error(resultObj.getString("msg"));
        }
        List<PPBomVO> ppBomVOs = JSON.parseArray(resultObj.get("data").toString(), PPBomVO.class);
        if (ppBomVOs.size() > 0) {
            Long userId = ShiroUtils.getUserId();

            // 本地生产计划内码
            List<Long> localIdList = productionFeedingDOList.stream().map(ProductionFeedingDO::getId)
                    .collect(Collectors.toList());
            // K3Cloud生产计划内码
            List<Long> remoteIdList = ppBomVOs.stream().map(PPBomVO::getFInterID)
                    .collect(Collectors.toList());
            // 删除的 k3无，本地有
            List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e))
                    .collect(Collectors.toList());
            // 修改的（本地库有的，远端库有的）
            List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains)
                    .collect(Collectors.toList());
            //        // 新增的（本地库无的，远端库有的）
            remoteIdList.removeAll(updateIdList);
            if (deleteIdList.size() > 0) {
                //批量删除
                List<ProductionFeedingDO> productionFeedingDOS=productionFeedingDOList.stream().filter(e->deleteIdList.contains(e.getId())).collect(Collectors.toList());
                for (ProductionFeedingDO productionFeedingDO:productionFeedingDOS
                ) {
                    productionFeedingDO.setDelFlag(1);
                }
                List<Long> headIds = productionFeedingDOS.stream().map(ProductionFeedingDO::getId).collect(Collectors.toList());
                productionFeedingService.batchUpdate(productionFeedingDOS);
                productionFeedingDetailService.batchUpdateToDelFlagByMainId(headIds);
                log.info("批量删除");
            }
            Date date = new Date();
            if(updateIdList.size() > 0){
                List<PPBomVO> ppBomVOList = ppBomVOs.stream().filter(e -> updateIdList.contains(e.getFInterID())).collect(Collectors.toList());
                List<ProductionFeedingDO> productionFeedingDOS = productionFeedingDOList.stream().filter(e -> updateIdList.contains(e.getId())).collect(Collectors.toList());
                PPBomVO ppBomVO ;
                for (ProductionFeedingDO productionFeedingDO : productionFeedingDOS) {
                    ppBomVO = ppBomVOList.stream().filter(e->productionFeedingDO.getId().equals(e.getFInterID())).collect(Collectors.toList()).get(0);
                    productionFeedingDO.setAuditor(ppBomVO.getFCheckerID());
                    productionFeedingDO.setProductionPlanId(ppBomVO.getFICMOInterID());
                    productionFeedingDO.setMaterielId(ppBomVO.getFItemID());
                    //                productionFeedingDO.setProDept(ppBomVO.getFUnitID());
                    productionFeedingDO.setPlanCount(ppBomVO.getFAuxQty());
                    productionFeedingDO.setFeedingNo(ppBomVO.getFBillNo());
                    productionFeedingDO.setStatus(ppBomVO.getFStatus());
                    productionFeedingDO.setType(ppBomVO.getFType());
                    productionFeedingDO.setProDept(ppBomVO.getFWorkSHop());
                    productionFeedingDO.setUpdateBy(userId);
                    productionFeedingDO.setUpdateTime(date);
                    productionFeedingDO.setDelFlag(0);
                }
                productionFeedingService.batchUpdate(productionFeedingDOS);
                productionFeedingDetailService.batchRemoveByHeadId(updateIdList.toArray(new Long[0]));
                List<ProductionFeedingDetailDO> detailDOList = Lists.newArrayList();
                for (PPBomVO bomVO : ppBomVOList) {

                    List<PPBomEntryVO> entryVOS = bomVO.getPpBomEntryList();
                    for (PPBomEntryVO entryVO : entryVOS) {
                        ProductionFeedingDetailDO detailDO = new ProductionFeedingDetailDO();
                        detailDO.setHeadId(entryVO.getFInterID());
                        detailDO.setMaterielId(entryVO.getFItemID());
                        detailDO.setBatchNo(entryVO.getFBatchNo());
                        detailDO.setPlanFeeding(entryVO.getFQtyMust());
                        detailDO.setOutCount(entryVO.getFStockQty());
                        detailDO.setScrapCount(entryVO.getFDiscardQty());
                        detailDO.setUpdateBy(bomVO.getFBillerID());
                        detailDO.setUpdateTime(date);
                        detailDO.setDelFlag(0);
                        detailDOList.add(detailDO);
                    }
                }
                productionFeedingDetailService.batchSave(detailDOList);
            }
            if (remoteIdList.size() > 0) {
                List<PPBomVO> ppBomVOS = ppBomVOs.stream()
                        .filter(e -> remoteIdList.contains(e.getFInterID())).collect(Collectors.toList());
                List<ProductionFeedingDO> list = Lists.newArrayList();
                List<ProductionFeedingDetailDO> detailDOList = Lists.newArrayList();

                for (PPBomVO ppBomVO : ppBomVOS) {
                    ProductionFeedingDO productionFeedingDO = new ProductionFeedingDO();
                    productionFeedingDO.setId(ppBomVO.getFInterID());
                    productionFeedingDO.setCreateBy(ppBomVO.getFBillerID());
                    productionFeedingDO.setAuditor(ppBomVO.getFCheckerID());
                    productionFeedingDO.setProductionPlanId(ppBomVO.getFICMOInterID());
                    productionFeedingDO.setMaterielId(ppBomVO.getFItemID());
                    //                productionFeedingDO.setProDept(ppBomVO.getFUnitID());
                    productionFeedingDO.setPlanCount(ppBomVO.getFAuxQty());
                    productionFeedingDO.setFeedingNo(ppBomVO.getFBillNo());
                    productionFeedingDO.setCreateTime(ppBomVO.getFDate());
                    productionFeedingDO.setStatus(ppBomVO.getFStatus());
                    productionFeedingDO.setType(ppBomVO.getFType());
                    productionFeedingDO.setProDept(ppBomVO.getFWorkSHop());
                    productionFeedingDO.setUpdateBy(userId);
                    productionFeedingDO.setUpdateTime(date);
                    productionFeedingDO.setDelFlag(0);
                    list.add(productionFeedingDO);

                    List<PPBomEntryVO> entryVOS = ppBomVO.getPpBomEntryList();
                    for (PPBomEntryVO entryVO : entryVOS) {
                        ProductionFeedingDetailDO detailDO = new ProductionFeedingDetailDO();
                        detailDO.setHeadId(entryVO.getFInterID());
                        detailDO.setMaterielId(entryVO.getFItemID());
                        detailDO.setBatchNo(entryVO.getFBatchNo());
                        detailDO.setPlanFeeding(entryVO.getFQtyMust());
                        detailDO.setOutCount(entryVO.getFStockQty());
                        detailDO.setScrapCount(entryVO.getFDiscardQty());

                        detailDO.setCreateBy(ppBomVO.getFBillerID());
                        detailDO.setCreateTime(date);
                        detailDO.setUpdateBy(ppBomVO.getFBillerID());
                        detailDO.setUpdateTime(date);
                        detailDO.setDelFlag(0);
                        detailDOList.add(detailDO);
                    }
                }

                productionFeedingService.batchSave(list);
                productionFeedingDetailService.batchSave(detailDOList);
            }
            log.info("批量新增");
        }
        return R.ok();
    }
}
